import 'dart:async';
import 'dart:convert';
import 'dart:io';
import 'dart:typed_data';

import 'package:flutter/material.dart';
import 'package:hixing_app/const/gaps.dart';
import 'package:hixing_app/extensions/iterable_ext.dart';
import 'package:hixing_app/utils/screen_ui.dart';
import 'package:hixing_app/views/test_view/ble_machine/BleDataUtils.dart';
import 'package:rxdart/rxdart.dart';

class WifiIndex extends StatefulWidget {
  WifiIndex({this.address = ""});

  final String address;

  @override
  _WifiIndexState createState() => _WifiIndexState();
}

class _WifiIndexState extends State<WifiIndex> {
  StreamSubscription<Uint8List>? socketListen;
  Socket? socket;
  bool isFinish = false;

  //speed
  String speed = "";
  int startTime = 0;

  // 传输时间
  late int completeTime = 0;
  late Uint8List imageBytes;
  List<Uint8List> splitImgList = [];
  late int fileSize = 0;

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    // initSocket();
  }

  @override
  dispose() {
    socketListen?.cancel();
    socket?.destroy();
    super.dispose();
  }

  Future<void> readySend({int num = 1}) async {
    //打开大数据模式发送文件
    int sizeInKb = 1000; // 大小为1000KB
    int sizeInBytes = sizeInKb * 1024; // 转换为字节
    imageBytes = Uint8List(sizeInBytes * num); // 创建Uint8List
    fileSize = imageBytes.length ~/ 1024;
    String name = "sss";
    Uint8List nameList = utf8.encode(name);
    List<int> imgBytesLength = getImgBytesLength();
    List<int> sendList = BleDataUtils.transData([
      0x05, // 功能  bytes 1
      0x01, // state  bytes 1
      ...imgBytesLength, // img length data  bytes 4
      0x00, // Data5
      0x01, // mount
      ...nameList,
      0x00 // name
    ]);
    debugPrint("开启大数据模式指令：${sendList}");
    socketWrit(sendList, responseCallback: (value) {
      if (value[3] == 5 && value[4] == 1 && value[5] == 1) {
        // 启动大数据发送模式======
        debugPrint("开启大数据传输模式");
        // start send file
        sendFile();
      }
    });
  }

  Future<void> sendFile() async {
    startTime = DateTime.now().millisecondsSinceEpoch;
    List<int> dataList = [...getImgHeader(), ...imageBytes];
    socketWrit(dataList, responseCallback: (value) {
      if (value[3] == 5 && value[4] == 2) {
        // 传输结束
        print("传输结束：${value[5] == 1 ? "接收成功" : "接受失败"}");
        if (mounted) {
          if (value[5] == 1) {
            finishSend();
          }
        }
      }
    });
  }

  void finishSend() {
    isFinish = true;
    completeTime = DateTime.now().millisecondsSinceEpoch - startTime;
    speed = "${(fileSize / (completeTime * 0.001)).toStringAsFixed(2)}k/S";
    splitImgList.clear();
    setState(() {});
  }

// 生成图片64个头部
  List<int> getImgHeader() {
    int widthHigh = (200 >> 8) & 0xFF;
    int widthLow = 200 & 0xFF;
    int heightHigh = (200 >> 8) & 0xFF;
    int heightLow = 200 & 0xFF;
    List<int> imgBytesLength = getImgBytesLength();
    List<int> imgList = [
      0x10, //图片数据  1bytes
      widthHigh, // 宽高八位 1bytes
      widthLow, //宽低八位 1bytes
      heightHigh, // 高高八位 1bytes
      heightLow, // 高低八位 1bytes
      0x00, // 图片name 4bytes
      0x00, // 图片name 4bytes
      0x00, // 图片name 4bytes
      0x00, // 图片name 4bytes
      0x00, // PX分辨率 1bytes
      0x00, // D3 2 bytes
      0x00, // D3 2 bytes
      0x00, // D4 2 bytes
      0x00, // D4 2 bytes
      0x00, // D5 2 bytes
      0x00, // D5 2 bytes
      0x00, //Dir
      ...imgBytesLength
    ];
    int recoupNum = 64 - imgList.length;
    // // 补齐64个字节
    for (int i = 0; i < recoupNum; i++) {
      imgList.add(0x00);
    }
    return imgList;
  }

  // 获取图片长度，拼接请求头用
  List<int> getImgBytesLength() {
    // 所有包的请求头长度都要算回去
    int _listLength = imageBytes.length + 64;
    // 把文件长度转成4个bytes
    List<int> _imgBytesLength = BleDataUtils.intToNBytesHex(_listLength, 4);
    print("返回的字节数组长度值：${_listLength}");
    return _imgBytesLength;
  }

  Future<void> exitCommand() async {
    // 连接到服务器
    List<int> exitCommand = BleDataUtils.transData([
      0xFF, // 功能  bytes 1
    ]);
    socketWrit(exitCommand);
  }

  Future<void> checkSetting() async {
    List<int> checkSettingList =
        BleDataUtils.transData([0x00, 0x02, 0x00, 0x00, 0x00, 0x00]);
    socketWrit(checkSettingList);
  }

  socketWrit(
    List<int> data, {
    Function(Uint8List)? responseCallback,
  }) async {
    // 连接到服务器
    socket = await Socket.connect(widget.address, 1111);
    print('Connected to ${socket!.remoteAddress.address}:${socket!.port}');
    socket!.add(data);
    socketListen = socket!.listen(
      (val) async {
        debugPrint("接收下行机器响应返回的数据：$val");
        if (responseCallback != null) {
          responseCallback(val);
        }
        // 接收响应后，关闭服务器
        socket!.destroy();
      },
      onError: (error) {
        debugPrint(error);
        socket!.destroy();
      },
      onDone: () {
        debugPrint('Server left.');
        socket!.destroy();
      },
    );
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('WiFi链接设备传输'),
      ),
      body: Center(
          child: Column(
        children: [
          Text("当前的ip地址：${widget.address}"),
          ElevatedButton(
            onPressed: () {
              //调焦指令
              // initSocket();
              // writToCh(focusList);
            },
            child: Text("通过WiFi 通讯"),
          ),
          ElevatedButton(
            onPressed: () {
              //调焦指令
              exitCommand();
              // writToCh(focusList);
            },
            child: Text("退出指令"),
          ),
          ElevatedButton(
            onPressed: () {
              //调焦指令
              checkSetting();
              // writToCh(focusList);
            },
            child: Text("查询设置指令"),
          ),
          ElevatedButton(
            onPressed: () {
              readySend(num: 10);
            },
            child: Text("发送文件10M"),
          ),
          ElevatedButton(
            onPressed: () {
              readySend(num: 20);
            },
            child: Text("发送文件20M"),
          ),
          ElevatedButton(
            onPressed: () {
              readySend(num: 50);
            },
            child: Text("发送文件50M"),
          ),
          ElevatedButton(
            onPressed: () {
              readySend(num: 100);
            },
            child: Text("发送文件100M"),
          ),
          Text("文件大小：${fileSize}K"),
          Text("传输时间：${completeTime} ms"),
          Text("传输速度：${speed}"),
          Text("是否传输完成：${isFinish}"),
          Gaps.getVGap(ScreenUI.bottomSafeHeight + 20),
        ],
      )),
    );
  }
}
